# support command :
# repo init -u https://git.oschina.net/osc4colder/manifest.git
# repo sync
import os
import sys
import getopt
import subprocess
import xml.dom.minidom

MANIFEST_XML = "default.xml"
REPO_WORKSAPCE = ".repo"

#def parse xml
def _ManifestParse(xml_file_name):
    print("_ManifestParse: %s" %xml_file_name)
    doc = xml.dom.minidom.parse(xml_file_name)
    root = doc.documentElement
    print("root name: %s" %root.nodeName)

    remote = {}
    remoteNode = root.getElementsByTagName('remote')
    remote['name'] = remoteNode[0].getAttribute('name')
    remote['fetch'] = remoteNode[0].getAttribute('fetch')

    default = {}
    defaultNode = root.getElementsByTagName('default')
    default['remote'] = defaultNode[0].getAttribute('remote')
    default['revision'] = defaultNode[0].getAttribute('revision')
    default['j'] = defaultNode[0].getAttribute('sync-j')


    projects = []
    projectNodes = root.getElementsByTagName('project')
    for projectNode in projectNodes:
        projectName = projectNode.getAttribute('name')
        ProjectPath = projectNode.getAttribute('path')
        project = {}
        project['name'] , project['path'] = ( projectName, ProjectPath)

        projects.append(project)
    return remote, default, projects

# clone git repository
def _Clone(src, dest):
    process = subprocess.Popen(["git","clone", src, dest], shell=True, stdin=None, stdout=None, stderr=None)
    if process.pid <= 0:
        print("fatal: git clone error")
        return False
    process.wait()

    if process.returncode != 0:
        print("fatal: git clone result error")
        return False
    return True

# clone git repository
def _Pull(src, dest):
    process = subprocess.Popen(["git","pull"], shell=True, cwd= dest, stdin=None, stdout=None, stderr=None)
    if process.pid <= 0:
        print("fatal: git clone error")
        return False
    process.wait()

    if process.returncode != 0:
        print("fatal: git clone result error")
        return False
    return True

# init function
def _RepoInit():
    print("_RepoInit")
    opts, args = getopt.getopt(sys.argv[2:], "u:")

    for op, value in opts:
        if op == "-u":
            print("%s" % value)
            _Clone(value, REPO_WORKSAPCE)
            remote, default, projects = _ManifestParse(REPO_WORKSAPCE +"/"+ MANIFEST_XML)
            for project in projects:
                _Clone(remote['fetch'] + project['name'], project['path'])


# sync function
def _RepoSync():
    print("_RepoSync")
    remote, default, projects = _ManifestParse(REPO_WORKSAPCE +"/"+ MANIFEST_XML)
    for project in projects:
       _Pull(remote['fetch'] + project['name'], project['path'])

# parameter check
def _ParameterCheck():
    if len(sys.argv) < 2:
        print("Please input parameter!")
    else :
        if sys.argv[1] == "init":
            _RepoInit()
        elif sys.argv[1] == "sync":
            _RepoSync()
# repo in windows version check

def main():
    _ParameterCheck()

if __name__ == '__main__':
    main()
